package org.business.accounting.pages;

import java.util.Collection;

import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.business.accounting.beans.CartBean;
import org.business.accounting.beans.LogOutHelperBean;
import org.business.accounting.beans.RegistrationHelperBean;
import org.business.accounting.beans.UserBean;
import org.business.accounting.interfaces.Cart;
import org.business.accounting.interfaces.LogOutHelper;
import org.business.accounting.interfaces.RegistrationHelper;
import org.business.accounting.interfaces.User;
import org.business.accounting.service.UserDAO;

@SuppressWarnings("unused")
public class Registration {

	@ApplicationState
	private User user;
	
	@Property
	private boolean userExists;
	
	@ApplicationState
	@Property
	private Cart cart;
	
	private boolean cartExists;
	
	@Inject
	private UserDAO userDAO;
	
	@Inject
	private Messages messages;
	
	@Persist
	@Property
	private LogOutHelper logOutHelper;
	
	//
	// Registration
	//
	
	@Persist
	@Property
	private RegistrationHelper registrationHelper;
	
	@Property
	private User tmpUser;
	
	@Property
	private String exclude = "admin, spentMoney";
	
	@Property
	private String validatePassword;
	
	@Component(parameters = {
			"registrationHelper = registrationHelper",
			"exclude = exclude",
			"validatePassword = validatePassword"})
	private org.business.accounting.components.Registration registration;
	
	//
	// Geters and seters
	//
	
	public boolean isAdmin() {
		if (userExists) {
			return user.isAdmin();
		}
		return false;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	//
	// Event handlers
	//
	
	@SetupRender
	public void onSetupRender() {
		tmpUser = new UserBean();
		registrationHelper = new RegistrationHelperBean(userDAO);
		
		if (!cartExists) {
			cart = new CartBean();
		}
		
		logOutHelper = new LogOutHelperBean();
		logOutHelper.setCart(cart);
		if (userExists) {
			logOutHelper.setUser(user);
		}
	}
	
	public Collection<User> getUsers() {
		return userDAO.retrieve();
	}
	
	void onSuccess() {
		user = registrationHelper.getTmpUser();
	}
	
	Object onSubmitFromRegistrationForm() {
		User user = userDAO.get(tmpUser.getUserName());
		boolean isRegistered = user != null;
		
		if (!isRegistered) {
			userDAO.save(tmpUser);
			user = tmpUser;
		} else {
			//registration.recordError(messages.get("username-allready-exists"));
		}
		
		return Index.class;
	}
}
